package com.ruoyi.hqfinance.controller;

import cn.hutool.core.net.URLEncoder;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hqfinance.domain.HqBillCollect;
import com.ruoyi.hqfinance.domain.HqBillData;
import com.ruoyi.hqfinance.domain.HqBillDataShow;
import com.ruoyi.hqfinance.domain.HqBillNearlySevenDay;
import com.ruoyi.hqfinance.domain.vo.HqBillCollectExportVo;
import com.ruoyi.hqfinance.domain.vo.HqBillCollectVo;
import com.ruoyi.hqfinance.domain.vo.HqBillDataShowVo;
import com.ruoyi.hqfinance.service.HqBillCollectService;
import com.ruoyi.logistic.domain.HqBillCollectCardAndSevenCache;
import com.ruoyi.logistic.domain.PageInfo;
import com.ruoyi.logistic.mapper.HqBillCollectCardAndSevenCacheMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/hq/billCollect")
@Api(tags = "总部财务-网点账单")
public class HqBillCollectController {
    @Autowired
    private HqBillCollectService hqBillCollectService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HqBillCollectCardAndSevenCacheMapper hqBillCollectCardAndSevenCacheMapper;

//    @ApiOperation("设置缓存")
//    @GetMapping("/setCache")
    public R setCache(){
        hqBillCollectService.setCache();
        return R.ok();
    }
    
    @ApiOperation("数据汇总")
    @PostMapping("/collect")
    public R collect(@RequestBody HqBillCollectVo vo){
        if (vo != null){
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }else {
            return R.ok("请传入必要的时间参数");
        }
        List<HqBillCollect> billCollectList = hqBillCollectService.collect(vo);
        if (billCollectList == null || billCollectList.size() == 0){
            return R.fail("暂无数据");
        }else {
            return R.ok(PageInfo.info(billCollectList));
        }
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public void export(@RequestBody HqBillCollectExportVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        String fileName = "attachment;filename=" + URLEncoder.createDefault().encode("网点账单", Charset.forName("utf-8")) + ".xlsx";
        response.setHeader("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        List<HqBillCollect> list = hqBillCollectService.collectExport(vo);
//        ExcelUtil<HqBillCollect> util = new ExcelUtil(HqBillCollect.class);
//        util.exportExcel(response, list, "网点账单");
//        String fileName = "网点账单.xlsx";
//        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + "\"");
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

        // 直接传递HttpServletResponse的getOutputStream到服务层方法
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        hqBillCollectService.collectExport(vo, outputStream);
    }



    @ApiOperation("各费用项收支")
    @PostMapping("/billDataShow")
    public R billDataShow(@RequestBody HqBillDataShowVo vo){
        List<HqBillDataShow> dataShowList = hqBillCollectService.billDataShow(vo);
        if (dataShowList == null || dataShowList.size() == 0){
            return R.ok("暂无数据");
        }else {
            String[] s = {"奖惩","面单","派费","中转","总部市场","其他"};
            for (int i = 0; i < 6; i++) {
                HqBillDataShow hqBillDataShow = dataShowList.get(i);
                hqBillDataShow.setTypeName(s[i]);
            }
            return R.ok(dataShowList);
        }
    }

    @ApiOperation("近七天趋势")
    @GetMapping("/nearlySevenDay")
    public R nearlySevenDay(@RequestParam("costBigKind") String costBigKind){
        List<HqBillNearlySevenDay> nearlySevenDays = hqBillCollectService.nearlySevenDay(costBigKind);
        if (nearlySevenDays == null || nearlySevenDays.size() == 0){
            return R.ok("暂无数据");
        }else {
            return R.ok(nearlySevenDays);
        }
    }

    @ApiOperation("卡片和近七天趋势图")
    @PostMapping("/cardAndSeven")
    public R cardAndSeven(@RequestBody HqBillDataShowVo vo){
        HqBillCollectCardAndSevenCache cache = new HqBillCollectCardAndSevenCache();
        cache.setCollecttype(vo.getCollectType());
        cache.setSevenmark(vo.getSevenMark());
        cache.setSettleNetworkNameId(vo.getSettleNetworkNameId());
        cache.setCreateTime(new Date());
        List<HqBillCollectCardAndSevenCache> hqBillCollectCardAndSevenCaches = hqBillCollectCardAndSevenCacheMapper.selectByAll(cache);
        if (hqBillCollectCardAndSevenCaches!=null && hqBillCollectCardAndSevenCaches.size()>0){
            HqBillData hqBillData = JSON.parseObject(hqBillCollectCardAndSevenCaches.get(0).getRespData(), HqBillData.class);
            System.out.println("从缓存中获取的数据");
            return R.ok(hqBillData);
        }
        System.out.println("查询接口获取的数据");
        return R.ok(hqBillCollectService.data(vo));
    }


    @ApiOperation("缓存卡片和近七天趋势图数据")
    @PostMapping("/cardAndSevenCache")
    public R cardAndSevenCache(){
        Integer[] collectTypes = {1,2,3};
        String[] settleNetworkNameIds = {"辽宁盘锦公司"};
        String[] sevenMarks = {"all"};
        HqBillDataShowVo vo;
        for (Integer collectType : collectTypes) {
            for (String settleNetworkNameId : settleNetworkNameIds) {
                for (String sevenMark : sevenMarks) {
                    vo = new HqBillDataShowVo();
                    vo.setCollectType(collectType);
                    vo.setSettleNetworkNameId(settleNetworkNameId);
                    vo.setSevenMark(sevenMark);
                    HqBillData data = hqBillCollectService.data(vo);
                    
                    byte[] result = JSON.toJSONString(data).getBytes();
                    HqBillCollectCardAndSevenCache cache = new HqBillCollectCardAndSevenCache();
                    cache.setCollecttype(collectType);
                    cache.setSettleNetworkNameId(settleNetworkNameId);
                    cache.setSevenmark(sevenMark);
                    cache.setRespData(result);
                    
                    hqBillCollectCardAndSevenCacheMapper.insertSelective(cache);
                    
                }
            }
        }
        return R.ok();
    }
}
